package com.bwie.bargain.service.impl;

import cn.hutool.core.date.DateUtil;
import com.bwie.bargain.dao.BargainDownDao;
import com.bwie.bargain.dao.HelpDao;
import com.bwie.bargain.entity.BargainDownEntity;
import com.bwie.bargain.entity.HelpEntity;
import com.bwie.common.utils.Md5Utils;
import com.bwie.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.common.utils.PageUtils;
import com.bwie.common.utils.Query;

import com.bwie.bargain.dao.BargainDownRecordDao;
import com.bwie.bargain.entity.BargainDownRecordEntity;
import com.bwie.bargain.service.BargainDownRecordService;
import org.springframework.transaction.annotation.Transactional;


@Service("bargainDownRecordService")
public class BargainDownRecordServiceImpl extends ServiceImpl<BargainDownRecordDao, BargainDownRecordEntity> implements BargainDownRecordService {

    @Autowired
    BargainDownRecordDao bargainDownRecordDao;

    @Autowired
    BargainDownDao bargainDownDao;

    @Autowired
    HelpDao helpDao;

    @Autowired
    StringRedisTemplate redisTemplate;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<BargainDownRecordEntity> page = this.page(
                new Query<BargainDownRecordEntity>().getPage(params),
                new QueryWrapper<BargainDownRecordEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R addrecord(Map<String, Object> params) {

        //获取用户id和商品id
        String user = (String) params.get("user");
        String good = (String) params.get("good");

        BargainDownEntity goodsid = bargainDownDao.selectOne(new QueryWrapper<BargainDownEntity>().eq("goods_id", good));
        if (goodsid.getStartTime().getTime()>System.currentTimeMillis() || goodsid.getEndTime().getTime()<System.currentTimeMillis())
          return R.error("请在活动时间砍价"+DateUtil.format(goodsid.getStartTime(), "yyyy-MM-dd HH:mm:ss")+"——"+DateUtil.format(goodsid.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
        //砍价记录是否已经生成
        BargainDownRecordEntity bargainDownRecordEntity = bargainDownRecordDao.selectOne(new QueryWrapper<BargainDownRecordEntity>().eq("user_id", user).
                eq("goods_id", good));
        //无记录才生成
        if (bargainDownRecordEntity==null){
            BargainDownRecordEntity bargain = new BargainDownRecordEntity();
            bargain.setUserId(Long.parseLong(user));
            bargain.setGoodsId(Long.parseLong(good));
            BargainDownEntity goods_id = bargainDownDao.selectOne(new QueryWrapper<BargainDownEntity>().eq("goods_id", good));
            bargain.setBargainiMethod(Long.parseLong(goods_id.getFlag()+""));
            bargain.setNowPrice(goods_id.getOriginalPrice());
            bargainDownRecordDao.insert(bargain);
            return R.ok().put("bargain",bargain.getGoodsId());
        }
        return R.error("已发起砍价");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R helpbargain(Map<String, Object> params) {
        String user = (String) params.get("user");
        String bargain = (String) params.get("bargain");
        String help = (String) params.get("help");

        HelpEntity helpEntity1 = helpDao.selectOne(new QueryWrapper<HelpEntity>().eq("userid", user).eq("helpid", help).eq("goodid", bargain));
        if (helpEntity1!=null)
            return R.error("不能重复砍价");

        //查询指定用户商品记录表
        BargainDownRecordEntity bargainDownRecordEntity = bargainDownRecordDao.selectOne(new QueryWrapper<BargainDownRecordEntity>().eq("user_id", user).eq("goods_id", bargain));
        Long bargainiMethod = bargainDownRecordEntity.getBargainiMethod();

        //查询指定商品的活动信息
        BargainDownEntity goods_id = bargainDownDao.selectOne(new QueryWrapper<BargainDownEntity>().eq("goods_id", bargain));

        //砍到指定的次数完成砍价
        if (bargainiMethod.equals(1L)){
            //砍到底价直接返回
            int floor = (int) Math.floor(goods_id.getBargainingRules());
            if (bargainDownRecordEntity.getBargainDown().equals(Long.parseLong(floor+"")))
               return R.error("已经砍价完成");

            //修改记录表中的砍价次数
            bargainDownRecordEntity.setBargainDown(bargainDownRecordEntity.getBargainDown()+1);
            bargainDownRecordDao.updateById(bargainDownRecordEntity);

            //向砍价中间表添加数据
            HelpEntity helpEntity = new HelpEntity();
            helpEntity.setUserid(Long.parseLong(user));
            helpEntity.setGoodid(Long.parseLong(bargain));
            helpEntity.setHelpid(Long.parseLong(help));
            helpDao.insert(helpEntity);

            //砍到指定次数 改变价格
            if (bargainDownRecordEntity.getBargainDown().equals(Long.parseLong(floor+""))){
                bargainDownRecordEntity.setNowPrice(goods_id.getBasePrice());
                bargainDownRecordDao.updateById(bargainDownRecordEntity);
            }
            return R.ok("砍价成功");

            //每次砍价指定范围的价格
        }else if (bargainiMethod.equals(2L)){

            //判断是否已经砍到底价
            if (bargainDownRecordEntity.getNowPrice().equals(goods_id.getBasePrice()))
            return R.error("已砍价完成");

            double result=0;
            //获取砍价的随机值
            Double max = goods_id.getBargainingRules();
            Random random = new Random();
            result=0.01D+(random.nextDouble()*(max-0.01D));
            result=(double) Math.round(result*100)/100;
            //随机减去的值小于活动底价则为底价 否则进行自减
            bargainDownRecordEntity.setNowPrice(bargainDownRecordEntity.getNowPrice()-result<goods_id.getBasePrice()?goods_id.getBasePrice():bargainDownRecordEntity.getNowPrice()-result);
            bargainDownRecordDao.updateById(bargainDownRecordEntity);

            //向砍价中间表添加数据
            HelpEntity helpEntity = new HelpEntity();
            helpEntity.setUserid(Long.parseLong(user));
            helpEntity.setGoodid(Long.parseLong(bargain));
            helpEntity.setHelpid(Long.parseLong(help));
            helpEntity.setRandprice(result);
            helpDao.insert(helpEntity);
            return R.ok("砍价成功");

        }
        return R.error("没有定义砍价方式");
    }

    @Override
    public R makeLink() {
        String s = UUID.randomUUID().toString().replaceAll("-", "");
        String link = Md5Utils.md5("link");
        redisTemplate.opsForValue().set("url", s+link,5, TimeUnit.MINUTES);
        return R.ok().put("url",s+link);
    }

    @Override
    public R checkLink(String url) {
        String url1 = redisTemplate.opsForValue().get("url");
        return url1.equals(url)?R.ok():R.error();
    }

    //测试生成随机数
    public static void main(String[] args) {
        /*Random rand = new Random();
        double MAX=0.3;
        double MIN=0.01;
        double result=0;
        for(int i=0; i<10; i++){
            result = MIN + (rand.nextDouble() * (MAX - MIN));
            result = (double) Math.round(result * 100) /100;
            System.out.println(result);
        }
        System.out.println("result = " + result);*/
        //System.out.println("UUID.randomUUID().toString() = " + UUID.randomUUID().toString());
    }

}